package com.baihui.taobao.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import ognl.Ognl;
import ognl.OgnlException;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jsoup.Jsoup;
import org.xml.sax.InputSource;

import com.baihui.crm.BaihuiResponse;
import com.baihui.crm.BaihuiSession;
import com.baihui.crm.DES;
import com.baihui.crm.TicketMgr;
import com.baihui.crm.export.ExportContacts;
import com.baihui.crm.export.ExportOrder;
import com.baihui.crm.export.ExportProduct;
import com.baihui.crm.util.BaihuiException;
import com.baihui.crm.util.BaihuiOptUtil;
import com.baihui.crm.util.ExportUtil;
import com.baihui.taobao.AppConstants;
import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.CommonDAO;
import com.baihui.taobao.db.DBConnectionMgr;
import com.baihui.taobao.db.ItemDao;
import com.baihui.taobao.db.MemberDAO;
import com.baihui.taobao.db.OrderDAO;
import com.baihui.taobao.db.TradeDAO;
import com.baihui.taobao.db.UserDAO;
import com.baihui.taobao.util.Util;
import com.baihui.taobao.vo.BOrder;
import com.baihui.taobao.vo.BShipping;
import com.baihui.taobao.vo.BTrade;
import com.baihui.taobao.vo.BUser;
import com.csvreader.CsvReader;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.TaobaoObject;
import com.taobao.api.domain.Trade;
import com.taobao.api.domain.User;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.response.UserGetResponse;

/**   
 *
 */
public class UploadCSVFileAction extends ActionSupport {
	/**
	 * 
	 */
	static Logger logger = Logger.getLogger(UploadCSVFileAction.class);
	private static final long serialVersionUID = 1L;
	private File uploadDetailList;
	private File uploadOrderList;
	private String baihuiUserId;
	private String sign;
	public static final String Contacts = "Contacts";
	public static final String Leads = "Leads";
	public static final String Orders = "SalesOrders";
	public static final String Products = "Products";
	protected BaihuiSession baihuiSession;
	protected TaoBaoSessionInfo taobaosession;
	protected Properties loader;
	CommonDAO commonDAO = new CommonDAO();
	Map<String, Object> topSessionMap;

	Map<String, Object> buyerMap = new HashMap<String, Object>();
	Map<String, Object> orderMap = new HashMap<String, Object>();
	Map<String, Object> shoppingMap = new HashMap<String, Object>();
	// Map<String, Object> tradeMap = new HashMap<String, Object>();
	Map<String, Object> tradeMap = new HashMap<String, Object>();
	// Map<String, String> existTradeMap = new HashMap<String, String>();
	private HttpServletRequest req = null;

	public File getUploadDetailList() {
		return uploadDetailList;
	}

	public void setUploadDetailList(File uploadDetailList) {
		this.uploadDetailList = uploadDetailList;
	}

	public File getUploadOrderList() {
		return uploadOrderList;
	}

	public void setUploadOrderList(File uploadOrderList) {
		this.uploadOrderList = uploadOrderList;
	}

	public String getBaihuiUserId() {
		return baihuiUserId;
	}

	public void setBaihuiUserId(String baihuiId) {
		this.baihuiUserId = baihuiId;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	@Override
	public String execute() throws Exception {

		req = ServletActionContext.getRequest();
		HttpSession session = req.getSession();
		taobaosession = (TaoBaoSessionInfo) req.getSession().getAttribute(
				baihuiUserId + AppConstants.DBTOPSESSIONINFO);
		if (taobaosession == null) {
			topSessionMap = commonDAO.findObject(
					"select * from topsession where baihuiuser = ? ",
					new Object[] { baihuiUserId });
			if (topSessionMap == null) {
				addActionError("【导入数据的用户不存在】");
				return SUCCESS;
			} else {
				taobaosession = new TaoBaoSessionInfo();
				taobaosession.setVisitor_id(Integer.parseInt(String
						.valueOf(topSessionMap.get("user_id"))));
				taobaosession.setCrmApiKey(String.valueOf(topSessionMap
						.get("crmapikey")));
				taobaosession.setParentbaihuiuserid(String
						.valueOf(topSessionMap.get("baihuiuser")));
				taobaosession.setParentbaihuipw(String.valueOf(topSessionMap
						.get("parentbaihuipw")));
			}
		}

		if (uploadDetailList != null && uploadOrderList != null) {
			if (readeCsv(uploadDetailList, uploadOrderList)) {
				// // 导入成交买家到crm
				// if (!exportUser(session)) {
				// addActionError("【导出成交买家时异常】");
				// }
				// // 导入订单信息到crm
				// if (exportOrder(session)) {
				// // 后续处理，比如更新宝贝信息
				// afterExported(Products, Long.valueOf(String
				// .valueOf(topSessionMap.get("user_id"))));
				// } else {
				// addActionError("【导出订单信息时异常】");
				// }
				BaihuiSession baihuiSession = initBaihuiSession(
						taobaosession);
				ExportProduct exportProduct = new ExportProduct(baihuiSession,
						taobaosession);
				List<Map> exportData = new ArrayList<Map>();
				exportData = exportProduct.findExportData(
						exportProduct.Products,
						new Long(taobaosession.getVisitor_id()));

				exportProduct.exportProduct(new Long(taobaosession
						.getVisitor_id()));

				// 导出成交用户信息
				ExportContacts exportContacts = new ExportContacts(
						baihuiSession, taobaosession);

				List<Map> allData = exportContacts.exportDealCustomer(new Long(
						taobaosession.getVisitor_id()));

				// 导出订单信息
				ExportOrder exportOrder = new ExportOrder(baihuiSession,
						taobaosession);
				exportOrder
						.exportOrder(new Long(taobaosession.getVisitor_id()));

			}
		} else {
			addActionError("【请正确选择CSV文件】");
		}

		return SUCCESS;
	}

	private boolean exportOrder(HttpSession session) throws Exception,
			BaihuiException {
		boolean isSuccess = false;
		//
		loader = null;
		// 导入订单到crm
		List<Map> exportOrder = commonDAO.findAllObject(
				"select * from tbtrade where baihuiid is null and userId= ? ",
				new Object[] { taobaosession.getVisitor_id() });

		int count = 100, startIndex = 0;
		List<Map> subOrder = Util.subList(exportOrder, startIndex, count);
		MemberDAO memberDAO = new MemberDAO();
		while (subOrder.size() > 0) {
			int index = 1;
			StringBuilder stringBuilder = new StringBuilder();
			String xmlDataString = "";
			boolean haveData = false;
			// 批量形成数据.
			stringBuilder.append("<" + "SalesOrders" + ">");
			for (Map map : subOrder) {
				BOrder temOrder = (BOrder) orderMap.get(String.valueOf(map
						.get("oid")));
				if (temOrder != null) {
					// BShipping temShipping = (BShipping) shoppingMap
					// .get(order[0]);
					// BOrder tmpOrder = (BOrder)
					// orderMap.get(order[0]);
					ItemDao itemDao = new ItemDao();
					if (temOrder.getOuterIid() != null
							&& !"".equals(temOrder.getOuterIid())) {
						Map titem = itemDao
								.findObject(
										"select * from titem where userid = ? and outer_id = ?",
										new Object[] {
												taobaosession.getVisitor_id(),
												temOrder.getOuterIid() });
						if (titem == null || titem.isEmpty()) {
							continue;
						}
						haveData = true;
						map.put("item", titem);

						Map temTrade = (Map) tradeMap.get(String
								.valueOf(temOrder.getParent().getTid()));
						map.put("trade", temTrade);

						// 根据配置得到百会字段与淘宝字段的映射
						xmlDataString = populate(map, "SalesOrders", index);
					}

				}

				// 调用导出数据，返回是否导出成功.
				if ("".equals(xmlDataString)) {
					continue;
				}
				stringBuilder.append(xmlDataString);
				index++;
			}
			stringBuilder.append("</" + "SalesOrders" + ">");
			if (haveData) {
				exportData(subOrder, stringBuilder, Orders, session);
			}
			long end2 = System.currentTimeMillis();
			// logger.info("插入zoho以及解析结果!共用时" + (end2 - start2) + "豪秒");
			startIndex = startIndex + count;
			subOrder = Util.subList(exportOrder, startIndex, count);
			index = 1;
		}
		isSuccess = true;
		return isSuccess;
	}

	private boolean exportUser(HttpSession session) throws Exception,
			BaihuiException {
		boolean isSuccess = false;
		// 导出成交买家数据到crm
		List<Map> exportUser = commonDAO
				.findAllObject(
						"select * from tbuser where baihuiid is null and sellerid= ? and  userType= ? and lotNo = ? ",
						new Object[] { taobaosession.getVisitor_id(),
								BUser.DEAL, 0 });

		int count = 100, startIndex = 0, totalNum = 0;
		List<Map> subUser = Util.subList(exportUser, startIndex, count);
		MemberDAO memberDAO = new MemberDAO();
		while (subUser.size() > 0) {
			int index = 1;
			StringBuilder stringBuilder = new StringBuilder();
			// 批量形成数据.
			stringBuilder.append("<" + "Contacts" + ">");
			for (Map map : subUser) {
				String[] order = (String[]) buyerMap.get(map.get("nick"));
				if (order != null && order.length > 0) {
					Map temTrade = (Map) tradeMap.get(order[0]);
					map.put("shipping", temTrade);

					String memberSql = "select * from tbcrmmember where userId= ? and buyerNick = ? ";
					Map<String, Object> members = memberDAO.findObject(
							memberSql,
							new Object[] { taobaosession.getVisitor_id(),
									order[1] });
					if (members == null)
						members = new HashMap<String, Object>();
					map.put("memberInfo", members);
				}

				// 根据配置得到百会字段与淘宝字段的映射
				String xmlDataString = populate(map, "Contacts", index);
				// 调用导出数据，返回是否导出成功.
				if (xmlDataString == null) {
					continue;
				}
				stringBuilder.append(xmlDataString);
				index++;
			}
			stringBuilder.append("</" + "Contacts" + ">");
			exportData(subUser, stringBuilder, Contacts, session);
			long end2 = System.currentTimeMillis();
			// logger.info("插入zoho以及解析结果!共用时" + (end2 - start2) + "豪秒");
			startIndex = startIndex + count;
			subUser = Util.subList(exportUser, startIndex, count);
			index = 1;
		}
		isSuccess = true;
		return isSuccess;
	}

	private void exportData(List<Map> subUser, StringBuilder stringBuilder,
			String type, HttpSession session) throws Exception, BaihuiException {
		String result = null;
		String selectResult = null;
		// taobaosession = (TaoBaoSessionInfo) topSessionMap;
		if (baihuiSession == null) {
			baihuiSession = initBaihuiSession(taobaosession);
		}
		if (subUser.get(0).get("baihuiid") != null) {
			result = BaihuiOptUtil.updateRecord(baihuiSession, type,
					stringBuilder.toString(), subUser.get(0).get("baihuiid")
							.toString());
		} else {
			Date date = new Date();
			result = BaihuiOptUtil.insertRecord(baihuiSession, taobaosession,
					type, stringBuilder.toString());
			selectResult = BaihuiOptUtil
					.selectRecord(baihuiSession, type, date);
		}
		// 解析结果.
		List<BaihuiResponse> ret = parse(result, selectResult, subUser, type);
		if (ret != null && ret.size() > 0) {
			if ("".equals(ret.get(0).getErrCode())) {
				List<String> updateBatch = new ArrayList<String>();
				for (BaihuiResponse baihuiResponse : ret) {
					String[] sql = getUpdateSQL(baihuiResponse.getBaihuiId(),
							baihuiResponse.getTaobaoId(), type,
							baihuiResponse.getTaobaoObject());
					if (sql != null && sql.length > 0) {
						for (String tmp : sql) {
							updateBatch.add(tmp);
						}
					}
				}
				// 更新记录
				if (updateBatch != null && updateBatch.size() > 0) {
					commonDAO.updateAndInsert(updateBatch, null);
				}
			} else {

				BaihuiException ex = new BaihuiException();
				ex.setErrCode(ret.get(0).getErrCode());
				throw ex;
			}
		}
	}

	public boolean readeCsv(File OrderDetailListPath, File OrderListPath) {

		boolean isSuccess = false;
		try {

			// Map<String, Object> buyerMap = new HashMap<String, Object>();
			// Map<String, Object> orderMap = new HashMap<String, Object>();
			// Map<String, Object> shoppingMap = new HashMap<String, Object>();

			// 将csv数据导到list中来
			List<String[]> OrderDetailList = new ArrayList<String[]>();
			List<String[]> OrderList = new ArrayList<String[]>();

			OrderDetailList = exportToList(new FileInputStream(
					OrderDetailListPath));
			OrderList = exportToList(new FileInputStream(OrderListPath));

			if (OrderList == null || OrderList.size() < 1) {
				addActionError("【ExportOrderList xxxxxx.csv文件没有内容】");
				return isSuccess;
			}
			if (OrderList.get(0).length != 32) {
				addActionError("【ExportOrderList xxxxxx.csv文件的列数不正确】");
				return isSuccess;
			}

			if (OrderDetailList == null || OrderDetailList.size() < 1) {
				addActionError("【ExportOrderDetailList xxxxxx.csv文件没有内容】");
				return isSuccess;
			}
			if (OrderDetailList.get(0).length != 10) {
				addActionError("【ExportOrderDetailList xxxxxx.csv文件的列数不正确】");
				return isSuccess;
			}

			// ExportOrderList处理成功
			if (parseOrderListFile(OrderList)) {

				isSuccess = parseOrderDetailListFile(OrderDetailList);
			}
			// addActionError("【文件导入成功！】");
		} catch (Exception ex) {
			System.out.println(ex);
		}
		return isSuccess;
	}

	private boolean parseOrderDetailListFile(List<String[]> OrderDetailList)
			throws Exception, SQLException {
		boolean isSuccess = false;
		ItemDao itemDao = new ItemDao();
		int count = 1000, startIndex = 0;
		List<String[]> subList = Util.subList(OrderDetailList, startIndex,
				count);
		while (subList.size() > 0) {

			// 更新商品使用.
			List<String> updateItems = new ArrayList<String>();
			List<TaobaoObject> bOrderList = new ArrayList<TaobaoObject>();
			List<Object[]> allInsertTitem = new ArrayList<Object[]>();
			List insertItemList = new ArrayList();
			List itemNameList = new ArrayList();
			try {
				for (int row = 0; row < subList.size(); row++) {
					// OrderDetailList文件的行记录
					String[] tradeDetailListString = subList.get(row);
					if (tradeDetailListString == null) {
						continue;
					}
					// 商家编码不能为空,如果为空不导入continue
					// if (tradeDetailListString[9] == null
					// || "".equals(tradeDetailListString[4])) {
					// continue;
					// }
					// OrderDetailList文件的中的交易id已经存在于中间库
					// if (existTradeMap.containsKey(tradeDetailListString[0]))
					// {
					// continue;
					// }
					// 没有这条记录的交易信息
					if (!tradeMap.containsKey(tradeDetailListString[0])) {
						continue;
					}

					BTrade trade = (BTrade) tradeMap
							.get(tradeDetailListString[0]);

					// 整理订单数据
					BOrder tmpOrder = new BOrder();
					orderMap.put(tradeDetailListString[0] + row, tmpOrder);
					tmpOrder.setUserId(Long.valueOf(String
							.valueOf(taobaosession.getVisitor_id())));
					tmpOrder.setBuyerNick(String.valueOf(trade.getBuyerNick()));
					tmpOrder.setNum(Long.valueOf(tradeDetailListString[3]));
					// 这是一个假的订单号，因为文件中取不到此数据
					tmpOrder.setOid(Long
							.valueOf(tradeDetailListString[0] + row));
					BTrade aBTrade = new BTrade();
					aBTrade.setTid(Long.valueOf(String.valueOf(trade.getTid())));
					tmpOrder.setParent(aBTrade);
					tmpOrder.setOuterIid(tradeDetailListString[4]);
					// 根据商家编码取出numiid
					String numiid = getNumiidByOuterId(tradeDetailListString[4]);
					// 如果numiid为空或者无效，再用标题去titem表里去查，没有说明宝贝不存在，新建一宝贝。
					if ("".equals(numiid)) {
						numiid = getProduct(tradeDetailListString[1]);
						if ("".equals(numiid)) {
							if (!insertItemList
									.contains(tradeDetailListString[0])
									&& !itemNameList
											.contains(tradeDetailListString[1])) {
								List paramList = new ArrayList();
								paramList.add(tradeDetailListString[1]); // 标题
								paramList.add(tradeDetailListString[2]); // 价格
								paramList.add(tradeDetailListString[0] + row); // 外部系统编号
								paramList.add(tradeDetailListString[0] + row); // numiid
								paramList.add(new Date()); // 创建
								paramList.add(new Date()); // 修改
								paramList.add(taobaosession.getVisitor_id()); // userid
								insertItemList.add(tradeDetailListString[0]);
								itemNameList.add(tradeDetailListString[1]);
								allInsertTitem.add(paramList.toArray());
							}

							// 将交易号作为商家编码
							tmpOrder.setNumIid(Long
									.valueOf(tradeDetailListString[0])+ row);
						} else {
							tmpOrder.setNumIid(Long.valueOf(numiid));
						}
					} else {
						tmpOrder.setNumIid(Long.valueOf(numiid));
					}
					tmpOrder.setPayment(tradeDetailListString[2]);
					tmpOrder.setPrice(tradeDetailListString[2]);
					tmpOrder.setStatus(ExportUtil
							.getOrderStatusByName(tradeDetailListString[8]));
					tmpOrder.setTitle(tradeDetailListString[1]);
					//
					tmpOrder.setTotalFee(String.valueOf(multip(
							Double.valueOf(tradeDetailListString[2]),
							Long.valueOf(tradeDetailListString[3]))));
					tmpOrder.setDiscountFee("0.00");
					tmpOrder.setLotNo(0);

					bOrderList.add(tmpOrder);
					updateItems
							.add("update titem set increamnum = (increamnum + "
									+ tradeDetailListString[3]
									+ "),exported = 2 where num_iid = '"
									+ tmpOrder.getNumIid() + "'");

				}
			} catch (Exception e) {
				throw e;
			}
			Connection cn = null;
			try {
				cn = DBConnectionMgr.getConnection();
				String sql = null;
				if (allInsertTitem != null) {
					sql = "insert into titem(title,price,outer_id,num_iid,created,modified,userid) values(?,?,?,?,?,?,?)";
					itemDao.updateAndInsert(null, sql, allInsertTitem);
					allInsertTitem.clear();
				}
				// cn.setAutoCommit(false);
				// 插入数据
				OrderDAO orderDAO = new OrderDAO();
				if (bOrderList != null && bOrderList.size() > 0) {
					orderDAO.insert(bOrderList, cn);
					bOrderList.clear();
				}
				if (updateItems != null && updateItems.size() > 0) {
					itemDao.updateAndInsert(updateItems, cn);
					updateItems.clear();
				}

				// cn.commit();
				isSuccess = true;
			} catch (Exception e) {
				if (cn != null)
					cn.rollback();
				throw e;
			} finally {
				if (cn != null)
					cn.close();
			}
			startIndex = startIndex + count;
			subList = Util.subList(OrderDetailList, startIndex, count);
		}
		return isSuccess;
	}

	private String getNumiidByOuterId(String outerIid) throws Exception {
		String numiidString = "";
		if (!"".equals(outerIid)) {
			List<String> values = commonDAO
					.findListString(
							" Select num_iid from titem where outer_id = ? and userid = ? ",
							new Object[] { outerIid,
									taobaosession.getVisitor_id() });

			if (values != null && values.size() > 0) {
				numiidString = values.get(0);
			} else {
				List<String> result = commonDAO
						.findListString(
								" Select numIid from tbsku where outerId = ? and userId = ? ",
								new Object[] { outerIid,
										taobaosession.getVisitor_id() });

				if (result != null && result.size() > 0) {
					numiidString = result.get(0);
				}
			}
		}

		return numiidString;
	}

	private String getProduct(String title) throws Exception {
		String numiidString = "";
		if (!"".equals(title)) {
			List<String> values = commonDAO.findListString(
					" Select num_iid from titem where title = ? and userid = ? ",
					new Object[] { title,taobaosession.getVisitor_id() });

			if (values != null && values.size() > 0) {
				numiidString = values.get(0);
			}
		}

		return numiidString;
	}

	private boolean parseOrderListFile(List<String[]> OrderList)
			throws Exception, SQLException {

		List<String> shoppingList = new ArrayList<String>();
		boolean isSuccess = false;
		int count = 1000, startIndex = 0;
		List<String[]> subList = Util.subList(OrderList, startIndex, count);
		while (subList.size() > 0) {
			// 更新商品使用.
			List<BUser> bUsersList = new ArrayList<BUser>();
			List<BTrade> bTradeList = new ArrayList<BTrade>();
			List<TaobaoObject> bShippingList = new ArrayList<TaobaoObject>();
			List<String> values = commonDAO.findListString(
					"Select tid from tbtrade where userId = ? ",
					new Object[] { taobaosession.getVisitor_id() });

			try {
				for (int row = 0; row < subList.size(); row++) {
					// OrderList文件的行记录
					String[] tradeListString = subList.get(row);
					// 交易号已经存在于中间库中
					if (values.contains(tradeListString[0])) {
						// existTradeMap.put(tradeListString[0],
						// tradeListString[0]);
						continue;
					}

					if (tradeListString[1] == null
							|| "".equals(tradeListString[1])) {
						continue;
					}
					// 宝贝标题为空
					if (tradeListString[19] == null
							|| "".equals(tradeListString[19])) {
						continue;
					}

					// 将物流的信息保存下来
					BShipping temShipping = new BShipping();
					// Map<String, Object> temShipping = new HashMap<String,
					// Object>();
					// temShipping.put("userId", taobaosession.getVisitor_id());
					temShipping.setUserId(Long.valueOf(String
							.valueOf(taobaosession.getVisitor_id())));
					temShipping.setBuyerNick(tradeListString[1]);
					// temShipping.put("buyerNick", tradeListString[1]);
					temShipping.setCompanyName(tradeListString[22]);
					// temShipping.put("companyName", tradeListString[22]);
					// temShipping.setOutSid(order);

					temShipping.setOrderCode(tradeListString[21]);
					// temShipping.put("orderCode", tradeListString[21]);
					temShipping.setTid(Long.valueOf(tradeListString[0]));
					// temShipping.put("tid", tradeListString[0]);
					// shoppingMap.put(tradeListString[0], temShipping);
					if (!shoppingList.contains(tradeListString[21])) {
						bShippingList.add(temShipping);
						shoppingList.add(tradeListString[21]);
					}

					// 交易信息map
					// Map<String, Object> temTrade = new HashMap();
					BTrade temTrade = new BTrade();
					// temTrade.put("tid", tradeListString[0]);
					temTrade.setTid(Long.valueOf(tradeListString[0]));
					temTrade.setUserId(Long.valueOf(String
							.valueOf(taobaosession.getVisitor_id())));
					// temTrade.put("userId", taobaosession.getVisitor_id());
					temTrade.setBuyerNick(tradeListString[1]);
					// temTrade.put("buyerNick", tradeListString[1]);
					// 返点积分
					temTrade.setBuyerObtainPointFee(Long
							.valueOf(tradeListString[7]));
					// temTrade.put("buyerObtainPointFee", tradeListString[7]);
					// 邮费
					temTrade.setPostFee(tradeListString[4]);
					// temTrade.put("postFee", tradeListString[4]);
					// 收货人的姓名
					temTrade.setReceiverName(tradeListString[12]);
					// temTrade.put("receiverName", tradeListString[12]);
					// 收货地址
					String[] address = tradeListString[13].split(" ");
					StringBuffer addBuffer = new StringBuffer();
					if (address != null) {
						if(address.length > 2){
							if (address[0] != null && !"".equals(address[0])) {
								// 收货人的所在省份
								temTrade.setReceiverState(address[0]);
								// temTrade.put("receiverState", address[0]);
							}
							if (address[1] != null && !"".equals(address[1])) {
								// 收货人的所在城市
								temTrade.setReceiverCity(address[1]);
								// temTrade.put("receiverCity", address[1]);
							}
							if (address[2] != null && !"".equals(address[2])) {
								// 收货人的所在地区
								temTrade.setReceiverDistrict(address[2]);
								// temTrade.put("receiverDistrict", address[2]);
							}
							if (address.length > 3) {
								for (int i = 3; i < address.length; i++) {
									addBuffer.append(address[i]);
								}
							}
						}else{
							addBuffer.append(tradeListString[13]);
						}
					}
					// 收货人的详细地址
					temTrade.setReceiverAddress(addBuffer.toString());
					// temTrade.put("receiverAddress", addBuffer.toString());
					// 收货人的手机号码
					temTrade.setReceiverMobile(tradeListString[16]);
					// temTrade.put("receiverMobile", tradeListString[16]);
					// 收货人的电话号码
					temTrade.setReceiverPhone(tradeListString[15]);
					// temTrade.put("receiverPhone", tradeListString[15]);
					temTrade.setCreated(convertDate(tradeListString[17],
							"yyyy-MM-dd HH:mm"));
					temTrade.setPayTime(convertDate(tradeListString[18],
							"yyyy-MM-dd HH:mm"));
					// 订单备注
					temTrade.setSellerMemo(tradeListString[23]);
					// 买家实际支付金额
					temTrade.setPayment(tradeListString[8]);
					temTrade.setStatus(ExportUtil
							.getOrderStatusByName(tradeListString[10]));
					temTrade.setTitle(tradeListString[19]);
					// temTrade.put("sellerMemo", tradeListString[23]);
					// temTrade.put("created", tradeListString[17]);
					// temTrade.put("payTime", tradeListString[18]);
					// temTrade.put("shipping", temShipping);
	
					// 判断用户在buyerMap里存不存在，存在忽略
					if (buyerMap.get(tradeListString[1]) == null) {
						User user = new User();
						// 判断这个订单的买家存不存在
						Map nickObject = commonDAO
								.findObject(
										"Select nick from tbuser where sellerid = ? and nick = ? ",
										new Object[] {
												taobaosession.getVisitor_id(),
												tradeListString[1] });

						user = getUserInfo(String.valueOf(tradeListString[1]));
						if(user == null){
							continue;
						}
					
						// 将OrderList文件的行记录存在一个map中，以买家会员名为主健
						buyerMap.put(tradeListString[1], tradeListString);
						BUser tmp = new BUser();
						Util.copy(tmp, user);
						tmp.setUserType(BUser.DEAL);
						tmp.setSellerid(Long.valueOf(String
								.valueOf(taobaosession.getVisitor_id())));
						tmp.setLotNo(0);
						tmp.setExported(0);
						// 用户不存在，需要插入中间库
						if (nickObject == null || nickObject.size() < 1) {
							bUsersList.add(tmp);
						}

					}
					tradeMap.put(tradeListString[0], temTrade);
					// 如果用户为空此交易就不导出
					bTradeList.add(temTrade);
				//System.out.println(temTrade.getTid());

				}

			} catch (Exception e) {
				throw e;
			}
			Connection cn = null;
			try {
				cn = DBConnectionMgr.getConnection();
				// cn.setAutoCommit(false);
				// 插入数据
				TradeDAO tradeDAO = new TradeDAO();
				if (bTradeList != null && bTradeList.size() > 0) {
					tradeDAO.insertTrade(bTradeList, cn);
					bTradeList.clear();
				}
				UserDAO userDAO = new UserDAO();
				if (bUsersList != null && bUsersList.size() > 0) {
					userDAO.insertUsers(bUsersList, cn);
					bUsersList.clear();
				}

				if (bShippingList != null && bShippingList.size() > 0) {
					userDAO.insert(bShippingList, cn);
					bShippingList.clear();
				}

				// cn.commit();
				isSuccess = true;
			} catch (Exception e) {
				if (cn != null)
					cn.rollback();
				throw e;
			} finally {
				if (cn != null)
					cn.close();
			}
			startIndex = startIndex + count;
			subList = Util.subList(OrderList, startIndex, count);
		}
		return isSuccess;
	}

	public Date convertDate(String adateStrteStr, String format) {
		java.util.Date date = null;
		try {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
			date = simpleDateFormat.parse(adateStrteStr);
		} catch (Exception ex) {
		}
		return date;
	}

	private List<String[]> exportToList(FileInputStream OrderDetailListFIS)
			throws FileNotFoundException, IOException {
		List<String[]> OrderDetailList = new ArrayList<String[]>();
		CsvReader reader = new CsvReader(OrderDetailListFIS, ',',
				Charset.forName("GBK")); // 一般用这编码读就可以了

		reader.readHeaders(); // 跳过表头 如果需要表头的话，不要写这句。

		while (reader.readRecord()) { // 逐行读入除表头的数据
			String[] datStrings = reader.getValues();
			if (datStrings[0].contains("+")) {
				addActionError("【请修改ExportOrderDetailList xxxxxx.csv第一列的科学计数法】");
				return OrderDetailList;
			}
			OrderDetailList.add(datStrings);
		}
		reader.close();
		return OrderDetailList;
	}

	private Map<String, Object> exportToMap(FileInputStream OrderListFIS)
			throws FileNotFoundException, IOException {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		CsvReader reader = new CsvReader(OrderListFIS, ',',
				Charset.forName("GBK")); // 一般用这编码读就可以了

		reader.readHeaders(); // 跳过表头 如果需要表头的话，不要写这句。

		while (reader.readRecord()) { // 逐行读入除表头的数据
			String[] datStrings = reader.getValues();
			// oid相同的记录，数据要合并
			if (dataMap.get(datStrings[0]) != null) {
				String[] temStrings = (String[]) dataMap.get(datStrings[0]);
				// 买家应付货款
				datStrings[3] = addObject(datStrings[3], temStrings[3]);
				datStrings[4] = addObject(datStrings[4], temStrings[4]);
				datStrings[5] = addObject(datStrings[5], temStrings[5]);
				datStrings[6] = addObject(datStrings[6], temStrings[6]);
				datStrings[7] = addObject(datStrings[7], temStrings[7]);
				// 买家实际支付金额
				datStrings[8] = addObject(datStrings[8], temStrings[8]);
				datStrings[9] = addObject(datStrings[9], temStrings[9]);
				// 购买数据
				datStrings[24] = addObject(datStrings[24], temStrings[24]);
				datStrings[28] = addObject(datStrings[28], temStrings[28]);
				datStrings[29] = addObject(datStrings[29], temStrings[29]);
			}
			if (datStrings[0].contains("+")) {
				addActionError("【请修改ExportOrderList xxxxxx.csv第一列的科学计数法】");
				return dataMap;
			}
			dataMap.put(datStrings[0], datStrings);
		}
		reader.close();
		return dataMap;
	}

	public User getUserInfo(String nickName) throws Exception {

		// TaoBaoSessionInfo sessionInfo =
		// (TaoBaoSessionInfo)req.getSession().getAttribute(baihuiUserId +
		// AppConstants.DBTOPSESSIONINFO);
		TaobaoClient client = new DefaultTaobaoClient(
				"http://gw.api.taobao.com/router/rest", "12531555",
				"c0e2ae267999e52e63fde23cfedc140f");
		UserGetRequest req = new UserGetRequest();
		req.setFields("user_id,uid,nick,sex,buyer_credit,seller_credit,location,created,last_visit,birthday,type,status,alipay_no,alipay_account,alipay_account,email,consumer_protection,alipay_bind");
		req.setNick(nickName);

		try {
			UserGetResponse response = client.execute(req);
			User user = response.getUser();
			return user;
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	public String addObject(String a, String b) {
		Long aLong = 0L;
		Long bLong = 0L;

		if (a != null && !"".equals(a)) {
			aLong = Long.valueOf(a);
		}
		if (b != null && !"".equals(b)) {
			bLong = Long.valueOf(b);
		}
		return String.valueOf(aLong + bLong);
	}

	/**
	 * 根据字段映射和类型形成XML字符串.
	 * 
	 * @param map
	 * @param type
	 * @return
	 */
	protected String populate(Map map, String type, int index) throws Exception {
		if (map == null || map.size() <= 0)
			return null;
		if (loader == null) {
			loader = new Properties();
			try {
				loader.load(this.getClass().getResourceAsStream(
						type + "_olddata.properties"));
			} catch (IOException e) {
				throw new Exception(e);
			}
		}
		if (loader != null) {
			return constructureXMLString(map, index);
		}
		return null;
	}

	/**
	 * 构造XML字符串,此方法只支持简单的构造，复杂的请继承来做。
	 * 
	 * @param source
	 * @param index
	 * @return
	 * @throws OgnlException
	 */
	protected String constructureXMLString(Map source, int index)
			throws Exception {
		StringBuilder xmlDataStr = new StringBuilder();
		xmlDataStr.append("<row no='" + index + "'>");
		Set set = loader.keySet();
		// 处理除分录意外的所有内容.
		String[] entryProps = getEntryKeys();

		Map<String, List> listMap = new HashMap<String, List>();
		// long start = System.currentTimeMillis();
		for (Object o : set) {
			// long start2 = System.currentTimeMillis();
			String key = (String) o; // key对应百会字段
			if (key != null && key.length() > 0) {
				// 如果是分录条目，先保存下来.
				boolean handle = true;
				if (entryProps != null && entryProps.length > 0) {
					for (String entryKey : entryProps) {
						if (key.startsWith(entryKey)) {
							List tmp = listMap.get(entryKey);
							if (tmp == null)
								tmp = new ArrayList();
							tmp.add(key);
							listMap.put(entryKey, tmp);
							handle = false;
							break;
						}
					}
				}
				if (!handle)
					continue;
				// 处理非分录的条目
				String expression = (String) loader.getProperty(key); // expression是一个ongl表达式，一般为对象的属性
				if (expression == null || expression.equals(""))
					continue;
				expression = parseExpression(expression, key, source);
				Object value = getValue(expression, source);
				value = format(value, key);
				xmlDataStr.append("<FL val=\"" + getKey(key) + "\">" + value
						+ "</FL>");
			}
			// long Orderend2 = System.currentTimeMillis();
			// logger.info("组装订单中非分录的条目中的" + getKey(key) + "时用时"+ (Orderend2 -
			// start2) + "豪秒");
		}
		// long Orderend = System.currentTimeMillis();
		// logger.info("组装订单中非分录的条目" + xmlDataStr + "用时"+ (Orderend - start) +
		// "豪秒");
		// 处理分录的情况
		// long start1 = System.currentTimeMillis();
		if (entryProps != null && entryProps.length > 0) {
			for (String entryKey : entryProps) {
				// 得到所有分录的Key
				List keys = listMap.get(entryKey);
				// 得到对应的值
				String entryValueKey = loader.getProperty(entryKey);
				// 处理分录的情况
				String entryXmlDataStr = constructureEntryXMLString(keys,
						source, entryKey);
				if (entryXmlDataStr != null && entryXmlDataStr.length() > 0) {
					xmlDataStr.append(entryXmlDataStr);
				}
			}
		}
		// long Orderend1 = System.currentTimeMillis();
		// logger.info("组装订单中分录的情况" + xmlDataStr +"用时" + (Orderend1 - start1) +
		// "豪秒");
		afterConstructureXMLString(xmlDataStr, source, set,
				taobaosession.getVisitor_id());
		xmlDataStr.append("</row>");
		return xmlDataStr.toString();
	}

	protected void afterConstructureXMLString(StringBuilder xmlDataStr,
			Map source, Set set, long userid) throws Exception {
		// 计算相关属性
		Map updateData = calcProperty(source, userid);
		if (updateData != null && updateData.size() > 0) {
			java.util.Iterator iter = updateData.keySet().iterator();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				xmlDataStr.append("<FL val=\"" + key + "\">"
						+ updateData.get(key) + "</FL>");
			}
		}
	}

	public Map calcProperty(Map map, long userid) throws Exception {
		TradeDAO tradeDAO = new TradeDAO();
		String nick = (String) map.get("nick");
		Map updateData = new HashMap();
		String sql = "select max(created) as lastTime from tbtrade where userId= ? and buyerNick = ? ";
		Map tmp = tradeDAO.findDate(sql, new Object[] { userid, nick });
		Timestamp lastTime = (Timestamp) tmp.get("lastTime");
		// 初始值
		updateData.put("用户状态", "休眠");
		if (lastTime != null) {
			long now = System.currentTimeMillis();
			double ret = (now - lastTime.getTime()) / (24l * 60l * 60l * 1000l);
			int totalDay = new Double(ret).intValue();
			if (ret > (totalDay + 0.5))
				totalDay = totalDay + 1;
			updateData.put("休眠时间", totalDay);
			if (totalDay > 90) {
				updateData.put("用户状态", "休眠");
			} else {
				updateData.put("用户状态", "活跃");
			}
			// 最后一次成交时间
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			updateData.put("最后一笔成交时间", dateFormat.format(lastTime));
		}
		// 保存到exportrecord中
		// saveOrUpdateExportRecord(userid, lastTime, Contacts,
		// map.get("userId"));
		// 计算成交订单数
		sql = "select count(tbo.oid) as totalNum,sum(tbo.payment) as payment from tborder tbo where tbo.status = 'TRADE_FINISHED' and tbo.userId= ? and tbo.buyerNick = ? and (exported IS NULL OR exported >= 0) ";
		tmp = tradeDAO.findDate(sql, new Object[] { userid, nick });
		Long totalCount = (Long) tmp.get("totalNum");
		if (totalCount == null)
			totalCount = new Long(0);
		updateData.put("成交订单数", totalCount);
		// 累计消费金额
		// sql = "select sum(totalFee) as totalFee from tbtrade where userId=" +
		// userid + " and  buyerNick = '" + nick + "' ";
		// tmp = tradeDAO.findObject(sql);
		BigDecimal totalFee = (BigDecimal) tmp.get("payment");
		if (totalFee == null)
			totalFee = new BigDecimal(0);
		updateData.put("累计消费金额", totalFee);
		return updateData;
	}

	public void updateCalProperty(long userid, int lotNo) throws Exception {

		String sqlupdate = "select nick,userId,baihuiid from tbuser where exported = 2 and sellerid = "
				+ userid;
		UserDAO userDAO = new UserDAO();
		List<Map> updateDataList = userDAO.findAllObject(sqlupdate);
		// allData中存放的已经是最后一次更改时间不相等的记录了
		TradeDAO tradeDAO = new TradeDAO();
		if (updateDataList != null && updateDataList.size() > 0) {
			for (Map map : updateDataList) {
				String nick = (String) map.get("nick");
				String baihuiid = (String) map.get("baihuiid");
				if (baihuiid == null || baihuiid.length() <= 0)
					continue;
				Map updateData = new HashMap();
				String sql = "select max(created) as lastTime from tbtrade where userId= ? and buyerNick = ? ";
				Map tmp = tradeDAO.findDate(sql, new Object[] { userid, nick });
				Timestamp lastTime = (Timestamp) tmp.get("lastTime");
				if (lastTime != null) {
					long now = System.currentTimeMillis();
					double ret = (now - lastTime.getTime())
							/ (24l * 60l * 60l * 1000l);
					int totalDay = new Double(ret).intValue();
					if (ret > (totalDay + 0.5))
						totalDay = totalDay + 1;
					updateData.put("休眠时间", totalDay);
					if (totalDay > 90) {
						updateData.put("用户状态", "休眠");
					} else {
						updateData.put("用户状态", "活跃");
					}
					// 最后一次成交时间
					SimpleDateFormat dateFormat = new SimpleDateFormat(
							"yyyy-MM-dd hh:mm:ss");
					updateData.put("最后一笔成交时间", dateFormat.format(lastTime));
				}
				// // TODO: exportrecord 表不再使用
				// saveOrUpdateExportRecord(userid, lastTime, Contacts,
				// map.get("userId"));
				// 计算成交订单数
				sql = "select count(tbo.oid) as totalNum,sum(tbo.payment) as payment from tborder tbo where tbo.status = 'TRADE_FINISHED' and tbo.userId= ? and tbo.buyerNick = ? and (exported IS NULL OR exported >= 0) ";
				tmp = tradeDAO.findDate(sql, new Object[] { userid, nick });
				Long totalCount = (Long) tmp.get("totalNum");
				if (totalCount == null)
					totalCount = new Long(0);
				updateData.put("成交订单数", totalCount);
				// 累计消费金额
				// sql =
				// "select sum(totalFee) as totalFee from tbtrade where userId="
				// + userid + " and  buyerNick = '" + nick + "' ";
				// tmp = tradeDAO.findObject(sql);
				BigDecimal totalFee = (BigDecimal) tmp.get("payment");
				if (totalFee == null)
					totalFee = new BigDecimal(0);
				updateData.put("累计消费金额", totalFee);

				StringBuilder xmlDataString = new StringBuilder();
				xmlDataString.append("<Contacts>");
				xmlDataString.append("<row no=\"1\">");
				java.util.Iterator iter = updateData.keySet().iterator();
				while (iter.hasNext()) {
					String key = (String) iter.next();
					xmlDataString.append("<FL val=\"" + key + "\">"
							+ updateData.get(key) + "</FL>");
				}
				xmlDataString.append("</row>");
				xmlDataString.append("</Contacts>");
				// System.out.println("计算相关属性:" + xmlDataString);
				BaihuiOptUtil.updateRecord(baihuiSession, Contacts,
						xmlDataString.toString(), baihuiid);
				// BaihuiOptUtil.deleteRecord(baihuiSession, Leads, baihuiid);
				String updateString = "update tbuser set exported = 1 where baihuiid = '"
						+ baihuiid + "'";
				userDAO.updateAndInsert(updateString, new Object[] {});
			}
		}
	}

	public String[] getEntryKeys() {
		return null;
	}

	protected String parseExpression(String expression, String key, Map source) {
		return expression;
	}

	/**
	 * expression如果以||分开，则分别取值，返回某个值.
	 * 
	 * @param expressioin
	 * @param source
	 * @return
	 * @throws Exception
	 */
	protected Object getValue(String expressioin, Map source) throws Exception {
		Map map = new HashMap();
		try {
			// map.put("session", this.taobaosession);
			if (expressioin.indexOf("~") > -1) {
				String[] args = expressioin.split("~");
				for (String arg : args) {
					Object tmp = Ognl.getValue(arg, map, source);
					if (tmp != null)
						return tmp;
				}
				return null;
			} else {
				return Ognl.getValue(expressioin, map, source);
			}
		} catch (OgnlException e) {
			throw new Exception(e);
		}
	}

	/**
	 * 格式化值
	 * 
	 * @param value
	 * @param baihuiField
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	protected String format(Object value, String baihuiField)
			throws UnsupportedEncodingException {
		if (value == null)
			return null;
		// 存在格式化配置
		if (value instanceof Timestamp) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			return simpleDateFormat.format((Timestamp) value);
		} else if (value instanceof Date) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"MM/dd/yyyy");
			return simpleDateFormat.format((Date) value);
		} else if (value instanceof Integer) {
			return String.valueOf(((Integer) value).intValue());
		} else if (value instanceof Long) {
			return String.valueOf(((Long) value).longValue()); // TODO
		} else if (value instanceof BigDecimal) {
			return String.valueOf(((BigDecimal) value).doubleValue());
		} else if (value instanceof Boolean) {
			return ((Boolean) value).booleanValue() ? "1" : "0";
		} else if (value instanceof String) {
			// return ((String) value);
			String string = Jsoup.parse((String) value).text();
			string = "<![CDATA[" + string + "]]>";
			return string;
		}
		return value.toString();
	}

	public String getKey(String key) {
		if (key != null && key.indexOf("@") > -1) {
			key = key.replace("@", " ");
		}
		return key;
	}

	/**
	 * 构造子分录的XML字符串
	 * 
	 * @param keys
	 * @param source
	 * @param entryKey
	 * @return
	 */
	protected String constructureEntryXMLString(List keys, Map source,
			String entryKey) throws Exception {
		return null;
	}

	/**
	 * 解析结果，返回成功或者失败.
	 * 
	 * @param response
	 * @return
	 */
	protected List<BaihuiResponse> parse(String response,
			String selectResponse, List<Map> subList, String type)
			throws Exception {
		if (response == null || response.length() <= 0 || subList == null
				|| subList.size() <= 0)
			return null;
		List<BaihuiResponse> parseRet = new ArrayList<BaihuiResponse>();
		// 是插入的情况
		Map map = new HashMap();
		if (selectResponse != null) {
			//
			// Map objectMap = new HashMap();
			// JSONObject jb = JSONObject.fromObject(selectResponse);
			// JSONObject ja =
			// jb.getJSONObject("response").getJSONObject("result");
			// JSONArray orderDetailArr =
			// ja.getJSONObject("SalesOrders").getJSONArray("row");
			// for(int j=0;j<orderDetailArr.size();j++){
			// objectMap.put(arg0, arg1)
			//
			// }
			BaihuiResponse baihuiResponse = new BaihuiResponse();
			StringReader reader = new StringReader(selectResponse);
			org.xml.sax.InputSource inputSource = new InputSource(reader);
			SAXBuilder sb = new SAXBuilder();
			Document doc = sb.build(inputSource);
			Element root = doc.getRootElement();
			Element error = root.getChild("nodata");
			if (error != null) {
				// System.out.println(response);
				Element code = error.getChild("code");
				Element msg = error.getChild("message");
				baihuiResponse.setErrCode(code.getText());
				parseRet.add(baihuiResponse);
				return parseRet;
			}
			map = getMapByDoc(doc, type);
		}
		try {
			StringReader reader = new StringReader(response);
			BaihuiResponse baihuiResponse = new BaihuiResponse();
			org.xml.sax.InputSource inputSource = new InputSource(reader);
			SAXBuilder sb = new SAXBuilder();
			Document doc = sb.build(inputSource);
			// 得到根元素和Result元素.
			Element root = doc.getRootElement();
			Element ret = root.getChild("result");
			Element error = root.getChild("error");
			if (error != null) {
				// System.out.println(response);
				Element code = error.getChild("code");
				Element msg = error.getChild("message");
				baihuiResponse.setErrCode(code.getText());
				parseRet.add(baihuiResponse);
				return parseRet;
			}
			if (ret != null) {
				// 得到Message信息
				Element message = ret.getChild("message");
				boolean isSuccess = message.getText().indexOf("successfully") > -1;
				// 得到所有的recordDetail
				List children = ret.getChildren("recorddetail");
				Element et = null;
				for (int i = 0; i < children.size(); i++) {
					baihuiResponse = new BaihuiResponse();
					et = (Element) children.get(i);
					baihuiResponse.setSuccess(isSuccess);
					baihuiResponse.setErrCode("");
					baihuiResponse
							.setTaobaoId(getTaoBaoId(subList.get(i), type));
					baihuiResponse.setTaobaoObject(subList.get(i));
					if ("Products".equals(type) || "SalesOrders".equals(type)) {
						baihuiResponse.setBaihuiId(String.valueOf(map
								.get(String.valueOf(baihuiResponse
										.getTaobaoId()))));
					} else if ("Contacts".equals(type)) {
						baihuiResponse
								.setBaihuiId(String.valueOf(map.get(String
										.valueOf(subList.get(i).get("nick")))));
					}

					List<Element> subElem = et.getChildren("FL");
					for (Element tmp : subElem) {
						String attrValue = tmp.getAttributeValue("val");
						if (attrValue != null) {
							// if (attrValue.equals("Id")) {
							// baihuiResponse.setBaihuiId(tmp.getText());
							// }
							if (attrValue.equals("Created Time")) {
								baihuiResponse.setCreateTime(Timestamp
										.valueOf(tmp.getText()));
							} else if (attrValue.equals("Modified Time")) {
								baihuiResponse.setModifyTime(Timestamp
										.valueOf(tmp.getText()));
							} else if (attrValue.equals("Created By")) {
								baihuiResponse.setCreateBy(tmp.getText());
							} else if (attrValue.equals("Modified By")) {
								baihuiResponse.setModifyBy(tmp.getText());
							}
						}
					}
					parseRet.add(baihuiResponse);
				}
			}
		} catch (JDOMException e) {
			throw new Exception(e);
		} catch (IOException e) {
			throw new Exception(e);
		}
		return parseRet;
	}

	private Object getTaoBaoId(Map map, String type) {
		if (map == null || map.size() <= 0)
			return null;
		if (Contacts.equals(type) || Leads.equals(type)) {
			return map.get("userId");
		} else if (Orders.equals(type)) {
			return map.get("oid");
		} else if (Products.equals(type)) {
			return map.get("num_iid");
		}
		return null;
	}

	private Map getMapByDoc(Document doc, String type) {
		if (doc == null)
			return null;
		Map resultMap = new HashMap();
		// 得到根元素和Result元素.
		Element root = doc.getRootElement();
		Element ret = root.getChild("result");
		Element typeEl = ret.getChild(type);
		if (ret != null) {
			// 得到Message信息
			List children = typeEl.getChildren("row");
			Element et = null;
			for (int i = 0; i < children.size(); i++) {
				et = (Element) children.get(i);
				List<Element> subElem = et.getChildren("FL");
				String keyString = "";
				String valueString = "";
				for (Element tmp : subElem) {
					String attrValue = tmp.getAttributeValue("val");
					if (attrValue != null) {
						if (Contacts.equals(type) || Leads.equals(type)) {
							if (("Last Name").equals(attrValue)) {
								keyString = tmp.getText();
								break;
							} else if ("CONTACTID".equals(attrValue)) {
								valueString = tmp.getText();
							}
						} else if (Orders.equals(type)) {
							if (("订单编号").equals(attrValue)) {
								keyString = tmp.getText();
								break;
							} else if ("SALESORDERID".equals(attrValue)) {
								valueString = tmp.getText();
							}
						} else if (Products.equals(type)) {
							if (("Product Code").equals(attrValue)) {
								keyString = tmp.getText();
								break;
							} else if ("PRODUCTID".equals(attrValue)) {
								valueString = tmp.getText();
							}

						}
					}
				}
				resultMap.put(keyString, valueString);
			}
		}
		return resultMap;
	}

	protected String[] getUpdateSQL(Object baihuiId, Object taobaoId,
			String type, Map taobaoObject) {
		if (taobaoId == null || taobaoId.toString().equals(""))
			return null;
		if (Contacts.equals(type) || Leads.equals(type)) {
			// Contacts的数据从tbuser中导入来的，并且userType=DEAL.
			return new String[] { "update tbuser set exported = 1,baihuiid='"
					+ baihuiId + "' where userid = " + taobaoId.toString()
					+ " and sellerid = " + taobaoObject.get("sellerid") };
		} else if (Orders.equals(type)) {
			String[] updateSqls = new String[1];
			if (taobaoObject.get("trade") != null) {
				Map map = (Map) taobaoObject.get("trade");
				if (map.get("endTime") != null) {
					updateSqls[0] = "update tborder set exported = 1,baihuiid='"
							+ baihuiId + "' where oid = " + taobaoId.toString();
				} else {
					updateSqls[0] = "update tborder set exported = 2,baihuiid='"
							+ baihuiId + "' where oid = " + taobaoId.toString();
				}
				return updateSqls;
			} else {
				return null;
			}
		} else if (Products.equals(type)) {
			String[] updateSqls = new String[1];
			updateSqls[0] = "update titem set exported = 1,baihuiid='"
					+ baihuiId + "' where num_iid = '" + taobaoId.toString()
					+ "'";
			return updateSqls;
		}
		return null;
	}

	// public static void main(String[] args) throws Throwable {
	// String csvFilePath = "e:/test.csv";
	// String csvFilePath1 = "e:/test1.csv";
	// readeCsv(csvFilePath,csvFilePath1);
	// // List resolve = resolveCsv("e:/test.csv");
	// }
	private void update(List<String> updateBatch, Connection cn, Long userid,
			String type) throws Exception {
		// 更新updateBatch
		CommonDAO commonDAO = new CommonDAO();
		commonDAO.updateAndInsert(updateBatch, null);
		// 增加或者更新该模块已经导出的最大时间.
	}

	/**
	 * 初始化百会Session
	 * 
	 * @param session
	 */
	private BaihuiSession initBaihuiSession(
			TaoBaoSessionInfo taoBaoSessionInfo) throws Exception {
		BaihuiSession baihuiSession;

		baihuiSession = new BaihuiSession();
		baihuiSession.setApiKey(taoBaoSessionInfo.getCrmApiKey());
		baihuiSession.setPassword(DES.decodePw(taoBaoSessionInfo
				.getParentbaihuipw()));
		baihuiSession.setUserName(taoBaoSessionInfo.getParentbaihuiuserid());
		TicketMgr ticketMgr = new TicketMgr();
		baihuiSession.setToken(taoBaoSessionInfo.getCrmApiKey());

		return baihuiSession;
	}

	protected void afterExported(String type, Long userid) throws Exception {

		try {
			// 更新宝贝的累计销量
			String sql = "select * from titem where exported = 2 and userId= ? ";
			CommonDAO dao = new CommonDAO();
			List<Map> updateItem = dao.findAllObject(sql,
					new Object[] { userid });

			// 更新百会商品数据
			for (Map item : updateItem) {
				if (!item.isEmpty()) {
					if (item.get("baihuiid") == null) {
						continue;
					}
					StringBuilder xmlDataString = new StringBuilder();
					xmlDataString.append("<Products>");
					xmlDataString.append("<row no=\"1\">");
					xmlDataString.append("<FL val=\"" + "累计销量" + "\">"
							+ item.get("increamnum") + "</FL>");
					xmlDataString.append("</row>");
					xmlDataString.append("</Products>");
					// System.out.println("更新商品数量:"+xmlDataString);
					String result = BaihuiOptUtil.updateRecord(baihuiSession,
							Products, xmlDataString.toString(),
							item.get("baihuiid").toString());

					// 解析结果.
					List<BaihuiResponse> ret = parse(result, null, updateItem,
							type);
					if (ret != null && ret.size() > 0) {
						for (BaihuiResponse baihuiResponse : ret) {
							if ("".equals(baihuiResponse.getErrCode())) {
								String updateSql = "update titem set exported = 1 where baihuiid = ? ";
								dao.updateAndInsert(updateSql,
										new Object[] { item.get("baihuiid") });
							}
						}
					}
				}
			}
			addActionError("【CSV文件导入成功】");
		} catch (Exception e) {
			logger.info("UploadCSVFileAction====" + e);
		}
	}

	public static double multip(double a, long b) {
		return (a * b);
	}

	public static void main(String[] ar) {
		double aLong = 1.2;
		long b = 1;
		multip(aLong, b);
	}

	public Date stringToDate(String dataString) throws ParseException {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:mm");
		Date date = simpleDateFormat.parse(dataString);

		return date;
	}
}
